package igedis

import (
	"gitee.com/tietang/terrace-go/v2/base"
	"gitee.com/tietang/terrace-go/v2/lib/gedis"
	log "github.com/sirupsen/logrus"
	"github.com/tietang/props/v3/kvs"
)

var redisCommands *gedis.RedisCommands

func Redis() *gedis.RedisCommands {
	base.Check(redisCommands)
	return redisCommands
}

type GedisStarter struct {
	base.BaseStarter
	redisCommands *gedis.RedisCommands
	opts          gedis.Options
}

func (s *GedisStarter) Init(ctx base.StarterContext) {
	conf := ctx.Props()
	s.opts = gedis.Options{}

	err := kvs.Unmarshal(conf, &s.opts, "redis")
	if err != nil {
		log.Error(err)
	}

	log.Infof("%+v\n", s.opts)

}

func (s *GedisStarter) Setup(ctx base.StarterContext) {
	var err error
	log.Info("setup redis")
	redisCommands, err = gedis.NewRedisCommands(&(s.opts))
	if err != nil {
		log.Error(err)
	}
	s.redisCommands = redisCommands
	log.Info(s.redisCommands.Ping().Result())
}

func (s *GedisStarter) Stop(ctx base.StarterContext) {
	s.redisCommands.Close()
}
